package com.auxgroup.hr.front.service.process.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import com.auxgroup.hr.front.service.process.WfSelHdrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.auxgroup.hr.front.commons.enums.WfStatusEnum;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.commons.utils.ObjectFieldUtils;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.JobCurrPrimary;
import com.auxgroup.hr.front.dao.domain.PsCWfEmpVw;
import com.auxgroup.hr.front.dao.domain.PsCWfPlaveDtl;
import com.auxgroup.hr.front.dao.domain.PsCWfSelHdr;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfPlaveDtlRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfSelHdrRepository;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.service.process.WfFileService;

/** 
 * @author lvliuhao 
 * @version 创建时间：2018年7月20日 下午4:55:28 
 * 类说明 
 */
@Service("wfSelHdrService")
public class WfSelHdrServiceImpl implements WfSelHdrService {
	private static final Logger logger = LoggerFactory.getLogger(WfSelHdrServiceImpl.class);
	
	@Autowired
	private PsCWfSelHdrRepository psCWfSelHdrRepository;
	
	@Autowired
	private PsCWfEmpVwRepository psCWfEmpVwRepository;
	
	@Autowired
	private WfFileService wfFileService;
	
	@Autowired
	private PsCWfPlaveDtlRepository psCWfPlaveDtlRepository;
	
	@Resource(name = "dozerMapper")
	protected IObjectMapper objectMapper;
	

	@Override
	public PsCWfSelHdr getSelHdrInfo(String transNum) {
		return psCWfSelHdrRepository.findOne(transNum);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public PsCWfSelHdr saveSelHdrInfo(List<PsCWfPlaveDtl> dtls,UserDTO user,String transNum,String leaveComments) {
		logger.info("save saveLaveHdrInfo start:",dtls);
		PsCWfSelHdr selHdr = psCWfSelHdrRepository.findOne(transNum);
		if(selHdr==null){
			selHdr = new PsCWfSelHdr();
			JobCurrPrimary primary = new JobCurrPrimary();
			primary.setEmplid(user.getEmplId());
			primary.setEmplRcd(new BigDecimal(0));
			PsCWfEmpVw emp = psCWfEmpVwRepository.findOne(primary);//获取个人信息内容
			selHdr.setcTransactionNbr(transNum);
			selHdr.setCreatedttm(new Timestamp(System.currentTimeMillis())); // 创建时间
			selHdr.setLastupddttm(new Timestamp(System.currentTimeMillis())); // 更新时间
			selHdr.setcWfStatus(WfStatusEnum.WF_STATUS_S.getStatus()); // 流程状态
			selHdr.setcWfType(WfTypeEnum.WF_STYPE_SEL.getType());// 流程类别
			selHdr.setCreatedBy(user.getOprId()); // 创建人用户
			selHdr.setLastupdoprid(user.getOprId()); // 更新者
			objectMapper.map(emp, selHdr,"notCopyNull_SelHdr");
			selHdr.setcOtherExplain(leaveComments);//销假事由
			ObjectFieldUtils.handleNullValue(selHdr);
		}
		selHdr.setcTotalDays(handleTotalDay(dtls));
		selHdr =  psCWfSelHdrRepository.save(selHdr);
		saveLaveDtls(dtls,transNum);
		return selHdr;
	}
	
	/**
	 * 计算totalday
	 * @param dtls
	 * @return
	 */
	private BigDecimal handleTotalDay(List<PsCWfPlaveDtl> dtls){
		if(dtls==null||dtls.isEmpty()){
			return new BigDecimal(0);
		}
		BigDecimal total = new BigDecimal(0);
		BigDecimal totalDay;
		for (PsCWfPlaveDtl dtl : dtls) {
			long day = (dtl.getStartDate().getTime()-dtl.getEndDate().getTime())/(24*60*60*1000);
			//如果最小请假单位为D，则每一条总天数=每日时长（C_DURATION_DAYS）*天数；
			if("D".equals(dtl.getCLevaeUnit())){
				totalDay = dtl.getCDurationDays().multiply(new BigDecimal(day+1));
				total.add(totalDay);
			}
			//如果最小请假单位为H，则每一条总天数=每日时长（C_DURATION_DAYS）*天数/8；
			if("H".equals(dtl.getCLevaeUnit())){
				totalDay = dtl.getCDurationDays().multiply(new BigDecimal(day+1));
				total.add(totalDay.divide(new BigDecimal(8)));
			}
		}
		return total;
	}
	
	/**
	 * 保存休假详情信息
	 * @param dtls
	 */
	private void saveLaveDtls(List<PsCWfPlaveDtl> dtls,String transNum){
		PsCWfPlaveDtl laveDtl = null;
		for (int i = 0; i < dtls.size(); i++) {
			laveDtl = dtls.get(i);
			laveDtl.setCTransactionNbr(transNum);
			laveDtl.setSeqnbr(new BigDecimal(i));
			ObjectFieldUtils.handleNullValue(laveDtl);
			psCWfPlaveDtlRepository.save(laveDtl);
		}
	}

	@Override
	public List<PsCWfPlaveDtl> getLaveDtls(String transNum) {
		PsCWfPlaveDtl queryDtl = new PsCWfPlaveDtl();
		queryDtl.setCTransactionNbr(transNum);
		return psCWfPlaveDtlRepository.findAll(Example.of(queryDtl));
	}
	
	
	@Override
	public void delSelHdr(String transNum) {
		psCWfPlaveDtlRepository.deleteByTransNum(transNum);
		wfFileService.delWfFiles(transNum, true);
		psCWfSelHdrRepository.deleteByTransNum(transNum);
	}

}
 